from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from store.models import StoreManagement
from users.models import User, RegisterCode, UserRole, Permission, RolePermission, Role, Menu, RoleMenu


# 分析创建用户序列化器的话可以使用到ModelSerializer

class CreateUserSerializer(serializers.ModelSerializer):
    """创建用户序列化器"""

    image_code_id = serializers.CharField(label='image_id', write_only=True)
    text = serializers.CharField(max_length=4, min_length=4, write_only=True)
    password2 = serializers.CharField(label="确认密码", write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段
    register_code = serializers.CharField(label='注册码', write_only=True)  # 增加注册码字段

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'text', 'image_code_id', 'token', 'register_code']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
        }

    def validate(self, attrs):
        if attrs["password"] != attrs["password2"]:
            raise serializers.ValidationError("确认密码不正确")

        """校验图片验证和"""
        image_code_id = attrs["image_code_id"]
        text = attrs["text"]
        register_code = attrs['register_code']

        # 校验register_code
        try:
            register_info = RegisterCode.objects.get(register_code=register_code)
        except Exception as e:
            raise serializers.ValidationError(e)
        if register_info is None:
            raise serializers.ValidationError("无效的注册码")
        if register_info.status is True:
            raise serializers.ValidationError("该注册码已被使用")

        # 查询redis中
        redis_conn = get_redis_connection("image_codes")
        try:
            true_text = redis_conn.get("img_%s" % image_code_id).decode()
            print(true_text)
        except Exception as e:
            raise serializers.ValidationError(e)
        if not true_text:
            raise serializers.ValidationError("无效的图片验证码")

        redis_conn.delete("img_%s" % image_code_id)

        if text.lower() != true_text.lower():
            raise serializers.ValidationError("图片验证码错误")

        return attrs

    def create(self, validate_data):
        """创建用户"""
        print("111")
        # 移除数据库不存在的属性
        validate_data.pop('text')
        validate_data.pop('image_code_id')
        validate_data.pop('password2')
        # print(validate_data.get("register_code"))

        user = super().create(validate_data)
        # user = User.objects.create(**validate_data)

        user.set_password(validate_data['password'])
        user.save()

        register_codes = RegisterCode.objects.get(register_code=validate_data.get("register_code"))
        register_codes.status = True
        register_codes.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token



        print(user.token)
        return user


class CreateRegisterCodeSerializer2(serializers.ModelSerializer):
    class Meta:
        model = RegisterCode
        fields = ['id', 'register_code', 'status']


class CreateRegisterCodeSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegisterCode
        fields = ['register_code',]

    # def validator(self, attrs):

class StoreNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreManagement
        fields = ['id', 'store']

class ReturnStaffAndStoreSerializer(serializers.ModelSerializer):
    storemanagement_set = StoreNameSerializer(many=True,read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'storemanagement_set']
        depth = 1





"""良宝serializer"""
class AddUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # password2 = serializers.CharField(label="确认密码", write_only=True)
        fields = ['id', 'username', 'password']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
        }

    # def validate(self, attrs):
    #     if attrs["password"] != attrs["password2"]:
    #         raise serializers.ValidationError("确认密码不正确")
    #     return attrs
    def create(self, validate_data):
        """创建用户"""
        print("111")
        # 移除数据库不存在的属性
        # validate_data.pop('password2')

        user = super().create(validate_data)
        # user = User.objects.create(**validate_data)
        user.set_password(validate_data['password'])
        print(user)
        user.save()
        return user


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        # fields = ['username']

class UserRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserRole
        fields = '__all__'
        # depth = 1


class UserRoleListSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserRole
        fields = '__all__'
        depth = 1




class UserRoleListSerializer2(serializers.ModelSerializer):
    class Meta:
        model = UserRole
        fields = ['id','role']
        # fields = '__all__'
        depth = 1


class UserListSerializer(serializers.ModelSerializer):
    # role_set = RoleSerializer()
    userrole_set = UserRoleListSerializer2(many=True,read_only=True)
    class Meta:
        model = User
        fields = ['id','username','is_superuser','email','last_login','date_joined','userrole_set']




class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'





class RolePermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = RolePermission
        fields = '__all__'


class RolePermissionListSerializer(serializers.ModelSerializer):
    class Meta:
        model = RolePermission
        fields = '__all__'
        depth = 1

class RoleSerializer(serializers.ModelSerializer):
    rolepermission_set = RolePermissionListSerializer(many=True, read_only=True)
    class Meta:
        model = Role
        fields = '__all__'

class MenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = Menu
        fields = '__all__'


class UserRolesListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = '__all__'
class UserRolesListSerializer2(serializers.ModelSerializer):
    class Meta:
        model = UserRole
        fields = '__all__'

class RolePermissionsListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'


class RolePermissionsListSerializer2(serializers.ModelSerializer):
    class Meta:
        model = RolePermission
        fields = '__all__'


class RoleMenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoleMenu
        fields = '__all__'
        # depth = 1


class RoleMenusListSerializer1(serializers.ModelSerializer):
    class Meta:
        model = Menu
        fields = '__all__'

class RoleMenusListSerializer2(serializers.ModelSerializer):
    class Meta:
        model = RoleMenu
        fields = '__all__'